package com.jihong.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class BookGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        ServerHttpRequest request = exchange.getRequest();
//        String url = request.getURI().toString();
//        //判断是否为登录或者注册路径
//        boolean loginRegisterUrl = url.contains("/book/user");
//        if(loginRegisterUrl || url.contains("/book/info/get")){
//            return chain.filter(exchange);
//        }
//        //验证token
//        List<String> token = request.getHeaders().get("token");
//        System.out.println(token);
//        if (token == null || token.size() == 0 ||  token.get(0) == null || token.get(0).trim().equals("")){
////            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);//给人家一个回应
//            ServerHttpResponse response = exchange.getResponse();
//            JSONObject message = new JSONObject();
//            message.put("status", -1);
//            message.put("data", "鉴权失败");
//            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
//            DataBuffer buffer = response.bufferFactory().wrap(bits);
////            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            //指定编码，否则在浏览器中会中文乱码
//            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
//            return response.writeWith(Mono.just(buffer));
//        }
        return chain.filter(exchange);


    }


        @Override
    public int getOrder() {
        return 0;
    }
}
